package com.example.loggingservice.consumer;

import com.alibaba.fastjson.JSON;
import com.example.common.event.OperationLogEvent;
import com.example.loggingservice.exception.OperationLogHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PreDestroy;

@Configuration
@Slf4j
public class RocketMQNativeConfig {

    @Value("${rocketmq.name-server}")
    private String nameServer;

    @Value("${rocketmq.consumer.group}")
    private String consumerGroup;

    private DefaultMQPushConsumer consumer;

    @Bean
    public DefaultMQPushConsumer operationLogConsumer(OperationLogHandler handler) throws MQClientException {
        // 1. 创建消费者实例
        consumer = new DefaultMQPushConsumer(consumerGroup);
        consumer.setNamesrvAddr(nameServer);
        consumer.subscribe("user-operation-log", "*");

        // 2. 注册消息监听器
        consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
            try {
                for (MessageExt msg : msgs) {
                    OperationLogEvent event = JSON.parseObject(msg.getBody(), OperationLogEvent.class);
                    handler.processOperationLog(event);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            } catch (Exception e) {
                log.error("处理消息失败", e);
                return ConsumeConcurrentlyStatus.RECONSUME_LATER; // 稍后重试
            }
        });

        // 3. 启动消费者
        consumer.start();
        log.info("✅ 原生RocketMQ消费者启动成功 | Group: {} | NameServer: {}", consumerGroup, nameServer);
        return consumer;
    }

    @PreDestroy
    public void destroy() {
        if (consumer != null) {
            consumer.shutdown();
            log.info("🚫 RocketMQ消费者已关闭");
        }
    }
}